﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Jenvin.Library.Functional
{
    class LambdaRecursion
    {
       public delegate TResult SelfApplicable<T, TResult>(SelfApplicable<T, TResult> self, T arg);
       public delegate TResult SelfApplicable<T1, T2, TResult>(SelfApplicable<T1, T2, TResult> self, T1 arg1, T2 arg2);

        /// <summary>
        /// 自己传自己实现递归
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="self"></param>
        /// <returns></returns>
        public static Func<T1, T2, TResult> Self<T1, T2, TResult>(
      SelfApplicable<T1, T2, TResult> self)
        {
            return (x, y) => self(self, x, y);
        }
        /// <summary>
        /// 自己传自己实现递归
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="self"></param>
        /// <returns></returns>
        public static Func<T, TResult> Self<T, TResult>(SelfApplicable<T, TResult> self)
        {
            return x => self(self, x);
        }
        /// <summary>
        /// 构造Y组合子
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="f"></param>
        /// <returns></returns>
        public static Func<T, TResult> Fix<T, TResult>(Func<Func<T, TResult>, Func<T, TResult>> f)
        {
            return x => f(Fix(f))(x);
        }

        public static Func<T1, T2, TResult> Fix<T1, T2, TResult>(Func<Func<T1, T2, TResult>, Func<T1, T2, TResult>> f)
        {
            return (x, y) => f(Fix(f))(x, y);
        }
    }
}
